#include "stdafx.h"
#include "SpriteInternal.h"
#include "Engine.h"
#include "Effect.h"
#include "VertexTypes.h"
#include "Texture.h"

unsigned int Graphics::SpriteInternal::ourIDCounter = 0;

Graphics::SpriteInternal::~SpriteInternal()
{

}

void Graphics::SpriteInternal::Render()
{
	Engine::GetDevice()->SetStreamSource(myVertexBuffer.streamNumber, myVertexBuffer.vertexBuffer, myVertexBuffer.byteOffset, myVertexBuffer.stride);
	Engine::GetDevice()->SetFVF(myVertexData.fvf);
	myEffect->GetEffect()->SetTexture("gDiffuse", myTexture->GetTexture());

	Vector2f position(GetRenderPos(myPosition));
	HRESULT hr = myEffect->GetEffect()->SetValue("gPosition", &position.x, sizeof(Vector2f));

	UINT iPass, cPasses;
	myEffect->GetEffect()->Begin(&cPasses, 0);
	for(iPass = 0; iPass < cPasses; iPass++)
	{
		myEffect->GetEffect()->BeginPass(iPass);
		Engine::GetDevice()->DrawPrimitive(myVertexData.primitiveType, 0, /*myVertexData.nrOfVertices*/ 2);
		myEffect->GetEffect()->EndPass();
	}
	myEffect->GetEffect()->End();
}

const unsigned int Graphics::SpriteInternal::GetID()
{
	return myID;
}

Graphics::SpriteInternal::SpriteInternal()
:myID(ourIDCounter++)
,myPosition(0,0)
{

}

bool Graphics::SpriteInternal::Init(const std::string& aFileName)
{
	myEffect = Engine::GetInstance()->GetEffectContainer().GetEffect("test.fx");
	myTexture = Engine::GetInstance()->GetTextureContainer().GetTexture(aFileName);

	Vector2f size = GetRenderSize(myTexture->GetSize());

	Utils::GrowingArray<VertexType::PosUV> vertices(4, 1);
	vertices.Add(VertexType::PosUV(Vector3f(-size.x, size.y, 0.5f), Vector2f(0.0f, 0.0f)));
	vertices.Add(VertexType::PosUV(Vector3f(size.x, size.y, 0.5f), Vector2f(1.0f, 0.0f)));
	vertices.Add(VertexType::PosUV(Vector3f(-size.x, -size.y, 0.5f), Vector2f(0.0f, 1.0f)));
	vertices.Add(VertexType::PosUV(Vector3f(size.x, -size.y, 0.5f), Vector2f(1.0f, 1.0f)));

	myVertexData.Init(vertices, D3DFVF_XYZ | D3DFVF_TEX1, D3DPT_TRIANGLESTRIP);
	DL_CHK_CRITICAL(myVertexBuffer.Init(myVertexData), "Failed to initialize VertexBuffer in sprite");

	return true;
}